package com.zfc.life.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * @author zfc
 * @Date 2024/5/23 14:45
 * @Description MD5Utils
 */
public class AESCipher {
    private static final String ALGORITHM = "AES";
    private static final byte[] keyValue =
            new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};

    /**
     * 加密密码
     *
     * @param valueToEncrypt
     * @return
     * @throws Exception
     */
    public static String encrypt_password(String valueToEncrypt) {
        SecretKeySpec key = new SecretKeySpec(keyValue, ALGORITHM);
        try {
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encValue = c.doFinal(valueToEncrypt.getBytes());
            String encryptedValue = Base64.getEncoder().encodeToString(encValue);
            return encryptedValue;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密密码
     * @param encryptedValue
     * @return
     */
    public static String decrypt_password(String encryptedValue) {
        SecretKeySpec key = new SecretKeySpec(keyValue, ALGORITHM);
        try {
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.DECRYPT_MODE, key);
            byte[] decordedValue = Base64.getDecoder().decode(encryptedValue);
            byte[] decValue = c.doFinal(decordedValue);
            String decryptedValue = new String(decValue);
            return decryptedValue;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String password = "zfc123456";
        String encrypt_password = encrypt_password(password);
        System.out.println("加密后的密码：" + encrypt_password);
        String decrypt_password = decrypt_password(encrypt_password);
        System.out.println("解密后的密码：" + decrypt_password);
    }
}
